package com.leve.control.controller;

import com.leve.control.constant.Constants;
import com.leve.control.constant.ErrorCode;
import com.leve.control.domain.Cuser;
import com.leve.control.domain.Device;
import com.leve.control.service.CuserService;
import com.leve.control.service.DeviceService;
import com.leve.control.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * app用户控制层（pc端）
 * @author whongyu
 * @create by 2019/6/17
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/api/cuser")
@Api(tags = {"pc:APP端用户相关接口服务"})
public class CuserController {

    @Autowired
    private CuserService cuserService;
    @Autowired
    private DeviceService deviceService;

    @ApiOperation(value = "app用户查询接口")
    @GetMapping(value = "/find")
    @ResponseBody
    public Result findCuser(@RequestBody Cuser cuser){
        log.info(Constants.REQ + ErrorCode.SUCCESS.getCode() + "|api/cuser/find|app用户查询接口,cuser={}: "+ cuser);
        try{
            List<Cuser> users = cuserService.findCuser(cuser);
            return new Result(ErrorCode.SUCCESS,users);
        }catch (Exception e){
            log.error(Constants.RES + ErrorCode.E_10001.getCode()+ "|api/cuser/find|app用户查询接口", e);
            return new Result(ErrorCode.E_10001);
        }
    }

    @ApiOperation(value = "app用户删除接口")
    @DeleteMapping(value = "/remove")
    @ResponseBody
    public Result removeCuser(@RequestParam String cuserId){
        log.info(Constants.REQ + ErrorCode.SUCCESS.getCode() + "|api/cuser/remove|app用户删除接口,cuserId={}: "+ cuserId);
        try{
            int i = cuserService.removeCuser(cuserId);
            if(i>0){
                return new Result(ErrorCode.SUCCESS);
            }else {
                return new Result(ErrorCode.E_20029);
            }
        }catch (Exception e){
            log.error(Constants.RES + ErrorCode.E_10001.getCode()+ "|api/cuser/remove|app用户删除接口", e);
            return new Result(ErrorCode.E_10001);
        }
    }

    @ApiOperation(value = "用户被授权设备查询接口")
    @GetMapping(value = "/query")
    @ResponseBody
    public Result queryCuserDevice(@RequestParam String userId){
        log.info(Constants.REQ + ErrorCode.SUCCESS.getCode() + "|api/cuser/query|用户被授权设备查询接口,cuserId={}: "+ userId);
        try{
            List<Device> devices = deviceService.findDevice(userId,-1);//只根据 userId 查询
            return new Result(ErrorCode.SUCCESS,devices);
        }catch (Exception e){
            log.error(Constants.RES + ErrorCode.E_10001.getCode()+ "|api/cuser/query用户被授权设备查询接口", e);
            return new Result(ErrorCode.E_10001);
        }
    }
}
